package com.apes.fn.scm.retailOrder.service;
import com.apes.fn.scm.contract.FnContract;
import com.apes.fn.scm.contract.FnContractRepository;
import com.apes.fn.scm.retailOrder.model.*;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.retailOrder.repository.PlatformFlowRepository;
import com.apes.fn.scm.retailOrder.repository.RetailOrderDiscountItemRepository;
import com.apes.fn.scm.retailOrder.repository.RetailOrderRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.pi.model.Timestamp;
import com.apes.pi.repository.TimestampRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.apes.framework.util.DateUtil.dateToDate;
import static com.apes.framework.util.DateUtil.format;

/**
 * @program: apes-server
 * @description 平台引流
 * @author: czs
 * @create: 2021-12-28 16:25
 **/
@Service("platformFlowService")
public class PlatformFlowService extends DomainService {

    @Autowired
    private TimestampRepository timestampRepository;
    @Autowired
    private PlatformFlowRepository platformFlowRepository;
    @Autowired
    private RetailOrderRepository retailOrderRepository;
    @Autowired
    private FnContractRepository fnContractRepository;
    @Autowired
    private RetailOrderDiscountItemRepository retailOrderDiscountItemRepository;


    public String savePlatformFlow(SimpleRequest request) {
        //首先获取到最新调用接口时间
        Timestamp timestamp = timestampRepository.findOne("ptf.platformFlow.statistic");
        Date startDate = new Date();
        startDate.setTime(Long.parseLong(timestamp.getTime()));
        Date endDate = new Date();
        String result = setPlatfromFlowItem(startDate,endDate);
        insetTimestamp(timestamp,endDate);
        return result;
        }


    public String savePlatformFlowTest(SimpleRequest request) {
        //首先获取到最新调用接口时间
//        Timestamp timestamp = timestampRepository.findOne("ptf.platformFlow.statistic");
        JSONObject jo = request.getJO();
        Long startTime = jo.getLong("startTime");
        Date startDate = new Date();
        startDate.setTime(startTime);
        Long endTime = jo.getLong("endTime");
        Date endDate = new Date();
        if (endTime!=null)endDate.setTime(endTime);
        if (false)return new Date().getTime()+"";
        String result = setPlatfromFlowItem(startDate,endDate);
//        insetTimestamp(timestamp,endDate);
        return result;
    }



    private String setPlatfromFlowItem(Date startDate,Date endDate) {

        List<RetailOrder> retailOrders = retailOrderRepository.findAllByCreateDate(startDate, endDate);

        if (retailOrders.isEmpty())return "没有零售单";
        invoke("ptf.platformFlowService.toSave", retailOrders);

//        extracted(retailOrders);

        return "成功";
    }

    private void extracted(SimpleRequest request) {
        RetailOrder retailOrder = request.getO(RetailOrder.class);
        List<RetailOrder> retailOrders = Collections.singletonList(retailOrder);
        saveOnlinePayFlow(retailOrders);

        saveOfflineCompensationFlow(retailOrders);

        savePlatformCouponSubsidy(retailOrders);
    }

    /**
     * 生成线上引流明细
     * @param retailOrders
     */
    private void saveOnlinePayFlow(List<RetailOrder> retailOrders){
        //过滤线上支付引流
        List<RetailOrderItem> onlinePayFlow = new ArrayList<>();
        retailOrders.stream()//过滤第一层条件
                .filter(retailOrder -> !"ePlus_Return".equals(retailOrder.getOrderType()))
                .forEach(retailOrder -> retailOrder.getSaleItems().stream()//第二层条件
                        .filter(retailOrderItem -> {
                            return retailOrderItem.getMainSalesman()!=null&&"00002256".equals(retailOrderItem.getMainSalesman().getId())&&retailOrderItem.getPriceTotal()>0
                                    && (retailOrderItem.getRetailDiscounts().stream().noneMatch(retailOrderDiscount -> ("001598".equals(retailOrderDiscount.getDiscountType().getId()) && "001600".equals(retailOrderDiscount.getDiscountType().getId()))));
                        }).forEach(onlinePayFlow::add));
        if (onlinePayFlow.isEmpty())return;
        //生成明细
        onlinePayFlow.forEach(retailOrderItem -> {
            PlatformFlow platformFlow = insetItemReport(retailOrderItem, new PlatformFlow());
            //取引流策略
            JSONObject platFromFlowPrice = getPlatFromFlowPrice(
                    MapUtil.mapper(
                            "conditionStrategyId", "VIP_01",
                            "COMPANY_ID", platformFlow.getCompany().getId(),
                            "CLASSIFY_ID",platformFlow.getProduct().getClassify().getId()));
            platformFlow.setFlowType("onlinePayFlow");
            if (platFromFlowPrice.getDouble("F001")==0) return;
            platformFlow.setOnlinePayFlow(platFromFlowPrice.getDouble("F001")*platformFlow.getSalesAmount());
            platformFlowRepository.saveAndFlush(platformFlow);
        });
    }

    /**
     * 生成线下引流明细
     * @param retailOrders
     */
    private void saveOfflineCompensationFlow(List<RetailOrder> retailOrders){
        //过滤线下支付引流
        Map<String, List<RetailOrder>> offlineCompensationFlow = retailOrders.stream().filter(RetailOrder::isPlatformFlow).collect(Collectors.groupingBy(retailOrder -> retailOrder.getCompany().getId()));
        if (offlineCompensationFlow.isEmpty())return;
        for (String companyId : offlineCompensationFlow.keySet()) {

            JSONObject platFromFlowPrice = getPlatFromFlowPrice(
                    MapUtil.mapper(
                            "conditionStrategyId", "VIP_02",
                            "COMPANY_ID", companyId));

            offlineCompensationFlow.get(companyId).forEach(retailOrder -> {
                PlatformFlow platformFlow = insetItemReport(retailOrder, new PlatformFlow());
                platformFlow.setFlowType("offlineCompensationFlow");
                double payAmount = retailOrder.getPaymentMethodSet().stream().mapToDouble(retailOrderPayMethod -> {
                    String id = retailOrderPayMethod.getPaymentMethodType().getId();
                    if (id.equals("12") || id.equals("05") || id.equals("10")) return retailOrderPayMethod.getAmount();
                    return 0.0;
                }).sum();
                double amount = platformFlow.getSalesAmount() - platformFlow.getDiscountAmount()-payAmount;
                Double f001 = platFromFlowPrice.get("F001")==null?0:platFromFlowPrice.getDouble("F001");
                platformFlow.setOfflineCompensationFlow(platFromFlowPrice.getDouble("F001")*amount);
                platformFlowRepository.saveAndFlush(platformFlow);

            });
        }
    }

    /**
     * 根据赋能合同取平台
     * @param companyId
     * @return
     */
    private PartyRole getPlatform(String companyId){
        List<FnContract> fnContracts = fnContractRepository.qryValidFnContract(companyId);
        if (fnContracts.isEmpty())return null;
        return fnContracts.get(0).getCompany();
    }

    /**
     * 生成平台券补贴
     * @param retailOrders
     */
    private void savePlatformCouponSubsidy(List<RetailOrder> retailOrders){
        //平台券补贴
        List<String> retailOrderIds = retailOrders.stream().map(RetailOrder::getId).collect(Collectors.toList());
        List<RetailOrderDiscountItem> retailOrderDiscountItems = retailOrderDiscountItemRepository.findAllByRetailOrderIdsAndPlatformSubsidy(retailOrderIds);
        retailOrderDiscountItems.forEach(retailOrderDiscountItem -> {
            RetailOrderItem retailOrderItem = retailOrderDiscountItem.getRetailDiscount().getRetailOrderItem();
            PlatformFlow platformFlow = insetItemReport(retailOrderItem, new PlatformFlow());
            platformFlow.setFlowType("platformSubsidy");
            platformFlow.setPlatformCouponId(retailOrderDiscountItem.getRetailDiscount().getCouponNumber());
            platformFlow.setPlatformCouponSubsidy(retailOrderDiscountItem.getPlatformSubsidy());

            platformFlowRepository.saveAndFlush(platformFlow);
        });
    }
    /**
     * 查询策略
     * @param param
     * @return
     */
    public JSONObject getPlatFromFlowPrice(Map param){
        param.put("SYS_RQ", new Date());
        Object obj = this.invoke("condition.execConditionStrategy", param);
        return new JSONObject(MapUtil.mapped(obj));
    }


    /**
     * 插入主表+商品信息
     * @param retailOrderItem
     * @param platformFlow
     * @return
     */
    private PlatformFlow insetItemReport(RetailOrderItem retailOrderItem,PlatformFlow platformFlow){
        platformFlow = insetItemReport(retailOrderItem.getOrder(),platformFlow);
        if (retailOrderItem.getPlatform()!=null)platformFlow.setPlatform(retailOrderItem.getPlatform());
        platformFlow.setProduct(retailOrderItem.getProduct());
        platformFlow.setSalesAmount(retailOrderItem.getPriceTotal());
        platformFlow.setDiscountAmount(retailOrderItem.getDiscountAmount());
        platformFlow.setPayAmount(0.0D);
        return platformFlow;

    }

    /**
     * 插入主表信息
     * @param order
     * @param platformFlow
     * @return
     */
    private PlatformFlow insetItemReport(RetailOrder order,PlatformFlow platformFlow){
        platformFlow.setOrderId(order.getId());
        platformFlow.setStatisticDate(DateUtil.dateToDate(order.getCreateDate(),DateUtil.SHOW_DATE_FORMAT));
        platformFlow.setOrderCreatorDate(order.getCreateDate());
        platformFlow.setDept(order.getDept());
        platformFlow.setCompany(order.getCompany());
        platformFlow.setCarLicense(order.getCustomerExpand().getCarLicense());
        platformFlow.setSalesAmount(order.getAmtTotal());
        platformFlow.setDiscountAmount(order.getDiscountAmount());
        platformFlow.setPayAmount(order.getPaymentMethodSet().stream().mapToDouble(RetailOrderPayMethod::getAmount).sum());
        platformFlow.setPlatform(getPlatform(order.getCompany().getId()));
        return platformFlow;
    }

    /**
     * 保存上次同步的时间
     * @param timestamp
     * @param endDate
     */
    private void insetTimestamp(Timestamp timestamp,Date endDate){
        timestamp.setTime(String.valueOf(endDate.getTime()));
        timestampRepository.saveAndFlush(timestamp);
    }



}
